﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

using RemotingFramework = DreamCube.Framework.Utilities.Remoting;
using SisenMESS_SinfoPlugIn.Remoting;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            //RemotingFramework.Client.Instance.InitialClient();
            //Remoting.TestClass obj = RemotingFramework.Server.Instance.CreateRemotingObj<Remoting.TestClass>(9002, "tcp", "172.16.46.69", true);
            //RemotingFramework.EventWrapper<String> wrapper = new RemotingFramework.EventWrapper<String>();
            //wrapper.TargetEvent += new Action<String>(wrapper_TargetEvent);
            //obj.GetMsg += new Remoting.TestClass.GetMsgEventHandler(wrapper.FireEvent);      
            //obj.SendMsg("黎鉴");
            //Console.ReadKey();

            ConnectServer("127.0.0.1", "9002");
            Console.ReadKey();
        }

        static SystemCommand systemCommand = null;
        /// <summary>
        /// 提醒服务器，登陆成功了（需要采用异步执行，预防客户端卡死了）
        /// </summary>
        public static void ConnectServer(String ip, String remotingPort)
        {
            Action<String, String> a = new Action<String, String>((s1, s2) =>
            {
                try
                {
                    Int32 port = 0;
                    IPAddress address = null;
                    if (IPAddress.TryParse(s1, out address) && Int32.TryParse(s2, out port))
                    {
                        //初始化remoting信道
                        RemotingFramework.Client.Instance.InitialClient();
                        //创建远程访问对象，等待接受服务器的命令
                        systemCommand = RemotingFramework.Server.Instance.CreateRemotingObj<SystemCommand>(port, "tcp", s1, true);

                        //事件2
                        RemotingFramework.EventWrapper<String> wrapper2 = new RemotingFramework.EventWrapper<String>();
                        wrapper2.TargetEvent += new Action<String>((commandText) =>
                        {
                            Console.WriteLine(commandText);
                        });
                        systemCommand.Command2 += new SystemCommand.SystemCommandHandler2(wrapper2.FireEvent);

                        //创建连接对象，告诉服务器端已连接
                        SystemConnection connection = RemotingFramework.Server.Instance.CreateRemotingObj<SystemConnection>(port, "tcp", s1, true);
                        connection.Connect();
                    }
                }
                catch (Exception)
                { }
            });
            a.BeginInvoke(ip, remotingPort, null, null);
        }

        static void wrapper_TargetEvent(String msg)
        {
            Console.WriteLine("接收到服务器消息：" + msg);
        }
    }
}
